package http

import (
	"Hypnos-Soundcore/components/log"
	"crypto/tls"
	"encoding/json"
	"errors"
	"fmt"
	"github.com/parnurzeal/gorequest"
	"net/http"
	"time"
)

const (
	DefaultTimeout = 2 * time.Second // 默认超时时间加长
)

// 获取超时间隔
func getTimeout(tm time.Duration) time.Duration {
	if tm > 0 {
		return tm * time.Second
	}
	return DefaultTimeout
}

func HttpGet(url string, params map[string]interface{}) (string, error) {
	return HttpGetSetTimeOut(url, params, 5*time.Second)
}

func HttpGetSetTimeOut(url string, params map[string]interface{}, timeout time.Duration) (string, error) {
	start := time.Now()

	request := gorequest.New()

	_, body, errs := request.Get(url).Query(params).Timeout(timeout).End()
	defer log.Info(url, "", fmt.Sprint(params), body, fmt.Sprintf("Time consuming:%d ", (time.Now().UnixNano()-start.UnixNano())/1000000))
	for _, err := range errs {
		if err != nil {
			log.Error("postJson url and params:", url, params, "request error: err=", errs)
			return "", errors.New("request error" + err.Error())
		}
	}

	return body, nil
}

func HttpGetForHeader(url string, params map[string]interface{}, header map[string]string) (string, error) {
	start := time.Now()
	request := gorequest.New().Get(url)
	if header != nil && len(header) > 0 {
		for key, value := range header {
			request = request.Set(key, value)
		}
	}
	_, body, errs := request.Query(params).Timeout(5 * time.Second).SetDebug(true).End()
	defer log.Info(url, "", fmt.Sprint(params), body, fmt.Sprintf("Time consuming:%d ", (time.Now().UnixNano()-start.UnixNano())/1000000))
	for _, err := range errs {
		if err != nil {
			log.Error("postJson url and params:", url, params, "request error: err=", errs)
			return "", errors.New("request error" + err.Error())
		}
	}

	return body, nil
}

func HttpPostJson(url string, params interface{}) (string, error) {
	start := time.Now()
	request := gorequest.New()

	_, body, errs := request.Post(url).Type("json").Timeout(5 * time.Second).Send(params).End()
	bodyStr, _ := json.Marshal(params)
	defer log.Info(url, "", string(bodyStr), body, fmt.Sprintf("Time consuming:%d ", (time.Now().UnixNano()-start.UnixNano())/1000000))
	for _, err := range errs {
		if err != nil {
			log.Error("postJson url and params:", url, params, "request error: err=", errs)
			return "", errors.New("request error" + err.Error())
		}
	}

	return body, nil
}

func HttpPostJsonIgnoreCertificate(url string, params interface{}) (string, error) {
	start := time.Now()
	request := gorequest.New().TLSClientConfig(&tls.Config{
		InsecureSkipVerify: true,
	})

	_, body, errs := request.Post(url).Type("json").Timeout(5 * time.Second).Send(params).End()
	bodyStr, _ := json.Marshal(params)
	defer log.Info(url, "", string(bodyStr), body, fmt.Sprintf("Time consuming:%d ", (time.Now().UnixNano()-start.UnixNano())/1000000))
	for _, err := range errs {
		if err != nil {
			log.Error("postJson url and params:", url, params, "request error: err=", errs)
			return "", errors.New("request error" + err.Error())
		}
	}

	return body, nil
}

//	func HttpPostJsonSetHeader(url string, params interface{}, header map[string]string) (string, error) {
//		start := time.Now()
//		request := gorequest.New()
//		request.Header = header
//		_, body, errs := request.Post(url).Type("json").Timeout(5 * time.Second).Send(params).End()
//		bodyStr, _ := json.Marshal(params)
//		defer log.Info(url, "", string(bodyStr), body, fmt.Sprintf("Time consuming:%d ", (time.Now().UnixNano()-start.UnixNano())/1000000))
//
//		for _, err := range errs {
//			if err != nil {
//				log.Error("postJson url and params:", url, params, "request error: err=", errs)
//				return "", errors.New("request error" + err.Error())
//			}
//		}
//		return body, nil
//	}
func HttpPostJsonSetTimeOut(url string, params interface{}, header map[string]string, timeout time.Duration) (string, error) {

	start := time.Now()
	request := gorequest.New()

	request = request.Post(url).Type("json").Timeout(timeout)
	for k, v := range header {
		request = request.Set(k, v)
	}
	_, body, errs := request.Send(params).End()
	bodyStr, _ := json.Marshal(params)
	defer log.Info(url, "", string(bodyStr), header, body, fmt.Sprintf("Time consuming:%d ", (time.Now().UnixNano()-start.UnixNano())/1000000))
	for _, err := range errs {
		if err != nil {
			log.Error("postJson url and params:", url, params, "request error: err=", errs)
			return "", errors.New("request error" + err.Error())
		}
	}
	return body, nil
}

func HttpPostJsonForHeader(url string, params interface{}, header map[string]string, response interface{}, timeout time.Duration) (int, error) {
	start := time.Now()
	request := gorequest.New().Timeout(getTimeout(timeout)).AppendHeader("Content-Type", "application/json").Post(url)
	if len(header) > 0 {
		for key, value := range header {
			request = request.Set(key, value)
		}
	}
	resp, body, errs := request.SendStruct(params).EndStruct(response)
	reqBodyStr, _ := json.Marshal(params)
	respStr, _ := json.Marshal(response)
	defer log.Info(url, "", header, string(reqBodyStr), string(respStr), fmt.Sprintf("Time consuming:%d ", (time.Now().UnixNano()-start.UnixNano())/1000000))
	httpStatus := 400
	if resp != nil {
		httpStatus = resp.StatusCode
		if resp.StatusCode >= http.StatusBadRequest {
			log.Error("resp=", resp)
			log.Error("body=", body)
		}
	}

	for _, err := range errs {
		if err != nil {
			log.Error("postJson url and params:", url, params, "request error: err=", errs)
			return httpStatus, errors.New("request error" + err.Error())
		}
	}

	return httpStatus, nil
}
